﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
namespace seejee_Backendium.Data.Services
{
    public class CharSaveService : ICharSaveService
    {
        private readonly string _connectionString;
        private readonly ILogger<ChartService> _logger;

        public CharSaveService(IConfiguration config, ILogger<ChartService> logger)
        {
            _connectionString = config.GetConnectionString("Default");
            _logger = logger;
        }

        /// <summary>
        /// 保存主配置
        /// </summary>
        public async Task<int> SaveBIMainTableAsync(string name, string createdAt, string BIMainTableId, string BackgroundColor, int iCusID)
        {
            const string sql = @"
        INSERT INTO SEBI_BIMainTable (Name, CreatedAt,ContainerId,BackgroundColor,iCusID)
        OUTPUT INSERTED.Id
        VALUES (@Name, @CreatedAt, @ContainerId,@BackgroundColor,@iCusID)";

            try
            {
                using var connection = new SqlConnection(_connectionString);
                return await connection.ExecuteScalarAsync<int>(sql, new
                {
                    Name = name,
                    CreatedAt = DateTime.Parse(createdAt),
                    ContainerId = BIMainTableId,  // 这里传入容器的OriginalId
                    BackgroundColor = BackgroundColor,
                    iCusID = iCusID
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存主表失败 | Name: {Name}, CusName: {CusName}", name);
                throw;
            }
        }

        /// <summary>
        /// 保存容器（支持嵌套）
        /// </summary>
        public async Task<int> SaveContainerAsync(
            DashboardContainerDto container,
            int mainTableId,
            int? parentContainerId = null)
        {
            const string sql = @"
INSERT INTO SEBI_Container (
    ContainerId, Type, Name, Span, Height, Title,
    BackgroundColor, HeaderColor, TitleColor, TitleSize,
    DividerColor, DividerGradient, DividerHeight,
    Sort, BIMainTableId
) OUTPUT INSERTED.Id
VALUES (
    @OriginalId, @Type, @Name, @Span, @Height, @Title,
    @BackgroundColor, @HeaderColor, @TitleColor, @TitleSize,
    @DividerColor, @DividerGradient, @DividerHeight,
    @Sort, @BIMainTableId
)";

            try
            {
                using var connection = new SqlConnection(_connectionString);
                var containerId = await connection.ExecuteScalarAsync<int>(sql, new
                {
                    OriginalId = container.Id,
                    container.Type,
                    container.Name,
                    container.Span,
                    container.Height,
                    container.Title,
                    container.BackgroundColor,
                    container.HeaderColor,
                    container.TitleColor,
                    container.TitleSize,
                    container.DividerColor,
                    container.DividerGradient,
                    container.DividerHeight,
                    container.Sort,
                    BIMainTableId = mainTableId,
                    ParentContainerId = parentContainerId
                });

                // 递归保存容器内子项
                if (container.children.Any())
                {
                    await SaveContainerItems(container.children, containerId, mainTableId);
                }

                return containerId;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存容器失败 | Cid: {Cid}", container.Id);
                throw new Exception($"保存容器 {container.Id} 失败", ex);
            }
        }

        /// <summary>
        /// 保存容器内所有子项
        /// </summary>
        private async Task SaveContainerItems(
            List<DashboardItemDto> items,
            int containerId,
            int mainTableId)
        {
            int sort = 1;
            int containerSort = 1; // 容器专用计数器（只对容器自增）
            foreach (var item in items)
            {
                // 容器
                if (item.Type == "container")
                {
                    var childContainer = new DashboardContainerDto
                    {
                        Type = "container",
                        Name = item.Title,
                        Span = int.Parse(item.Span.ToString()), // 明确转换
                        Height = int.Parse(item.Height.ToString()),
                        Title = item.Title,
                        BackgroundColor = item.BackgroundColor,
                        HeaderColor = item.HeaderColor,
                        TitleColor = item.TitleColor,
                        TitleSize = int.Parse(item.TitleSize.ToString()),
                        Sort = containerSort
                    };

                    await SaveContainerAsync(childContainer, mainTableId, containerId);
                    containerSort++; // 仅容器计数器自增（不影响子项）
                }
                // 翻牌器类型
                else if (new[] { "flopwithicon", "flopwithring", "digitalflop" }.Contains(item.Type))
                {
                    await SaveFlipNumberAsync(item, containerId, mainTableId, sort);
                }
                // 折线图
                else if (item.Type == "line")
                {
                    await SaveLineChartAsync(item, containerId, mainTableId, sort);
                }
                // 柱状图
                else if (item.Type == "bar")
                {
                    await SaveBarChartAsync(item, containerId, mainTableId, sort);
                }
                // 表格
                else if (item.Type == "table")
                {
                    await SaveTableAsync(item, containerId, mainTableId, sort);
                }
                // 圆饼图
                else if (item.Type == "pie")
                {
                    await SavePieChartAsync(item, containerId, mainTableId, sort);
                }
                // 环形图
                else if (item.Type == "ring")
                {
                    await SaveRingChartAsync(item, containerId, mainTableId, sort);
                }
                // 文本组件
                else if (item.Type == "text")
                {
                    await SaveTextAsync(item, containerId, mainTableId, sort);
                }
                sort++;
            }
        }

        /// <summary>
        /// 保存翻牌器子项
        /// </summary>
        public async Task SaveFlipNumberAsync(
            DashboardItemDto item,
            int containerId,
            int mainTableId,
            int sort)
        {
            const string sql = @"
INSERT INTO SEBI_FlipNumberConfig (
    cId, Type, Span, Height, TitleName, TitleColor, TitleSize,
    ValueColor, ValueSize, Unit, UnitSize, IconImage, IconColor,
    IconSize, RingColor, RingValue, IconPosition, ThousandSeparator,
    BackgroundColor, BackgroundStyle, Leftunit, Leftunitsize,
    cSql, BIMainTableId, ContainerId, Sort,layoutDirection,
    buttonshow,buttonname,buttonsql
) VALUES (
    @cId, @Type, @Span, @Height, @TitleName, @TitleColor, @TitleSize,
    @ValueColor, @ValueSize, @Unit, @UnitSize, @IconImage, @IconColor,
    @IconSize, @RingColor, @RingValue, @IconPosition, @ThousandSeparator,
    @BackgroundColor, @BackgroundStyle, @Leftunit, @Leftunitsize,
    @SqlList, @BIMainTableId, @ContainerId, @Sort,@layoutDirection,
    @buttonshow,@buttonname,@buttonsql
)";

            using var connection = new SqlConnection(_connectionString);
            await connection.ExecuteAsync(sql, new
            {
                cId = item.Id,
                item.Type,
                item.Span,
                item.Height,
                TitleName = item.Title,
                item.TitleColor,
                item.TitleSize,
                item.ValueColor,
                item.ValueSize,
                item.Unit,
                item.UnitSize,
                item.IconImage,
                item.IconColor,
                item.IconSize,
                item.RingColor,
                item.RingValue,
                item.IconPosition,
                item.ThousandSeparator,
                item.BackgroundColor,
                item.BackgroundStyle,
                item.Leftunit,
                item.leftunitsize,
                SqlList = JsonConvert.SerializeObject(item.SqlList),
                BIMainTableId = mainTableId,
                ContainerId = containerId,
                Sort = sort,
                item.layoutDirection,
                item.buttonshow,
                buttonname = JsonConvert.SerializeObject(item.buttonname),
                buttonsql = JsonConvert.SerializeObject(item.buttonsql),
            });
        }

        /// <summary>
        /// 保存折线图子项
        /// </summary>
        public async Task SaveLineChartAsync(
            DashboardItemDto item,
            int containerId,
            int mainTableId,
            int sort)
        {
            const string sql = @"
INSERT INTO SEBI_LineConfig (
    cId, Type, Span, Height, TitleName, TitleColor, TitleSize,
    ValueColor, Lines, XAxisData, Data,
    BackgroundColor, BackgroundStyle, SqlList,
    BIMainTableId, ContainerId, Sort
) VALUES (
    @cId, @Type, @Span, @Height, @TitleName, @TitleColor, @TitleSize,
    @ValueColor, @Lines, @XAxisData, @Data,
    @BackgroundColor, @BackgroundStyle, @SqlList,
    @BIMainTableId, @ContainerId, @Sort
)";

            using var connection = new SqlConnection(_connectionString);
            await connection.ExecuteAsync(sql, new
            {
                cId = item.Id,
                item.Type,
                item.Span,
                item.Height,
                TitleName = item.Title,
                item.TitleColor,
                item.TitleSize,
                item.ValueColor,
                Lines = JsonConvert.SerializeObject(item.Lines),
                XAxisData = JsonConvert.SerializeObject(item.XAxisData),
                Data = JsonConvert.SerializeObject(item.Data),
                item.BackgroundColor,
                item.BackgroundStyle,
                SqlList = JsonConvert.SerializeObject(item.SqlList),
                BIMainTableId = mainTableId,
                ContainerId = containerId,
                Sort = sort
            });
        }

        /// <summary>
        /// 保存柱状图子项
        /// </summary>
        public async Task SaveBarChartAsync(
            DashboardItemDto item,
            int containerId,
            int mainTableId,
            int sort)
        {
            const string sql = @"
INSERT INTO SEBI_BarConfig (
    cId, Type, Span, Height, TitleName, TitleColor, TitleSize,
    ValueColor, Bars, XAxisData, Data, BarCategoryGap, BarGap,
    BackgroundColor, BackgroundStyle, SqlList,
    BIMainTableId, ContainerId, Sort
) VALUES (
    @cId, @Type, @Span, @Height, @TitleName, @TitleColor, @TitleSize,
    @ValueColor, @Bars, @XAxisData, @Data, @BarCategoryGap, @BarGap,
    @BackgroundColor, @BackgroundStyle, @SqlList,
    @BIMainTableId, @ContainerId, @Sort
)";

            using var connection = new SqlConnection(_connectionString);
            await connection.ExecuteAsync(sql, new
            {
                cId = item.Id,
                item.Type,
                item.Span,
                item.Height,
                TitleName = item.Title,
                item.TitleColor,
                item.TitleSize,
                item.ValueColor,
                Bars = JsonConvert.SerializeObject(item.Bars),
                XAxisData = JsonConvert.SerializeObject(item.XAxisData),
                Data = JsonConvert.SerializeObject(item.Data),
                item.BarCategoryGap,
                item.BarGap,
                item.BackgroundColor,
                item.BackgroundStyle,
                SqlList = JsonConvert.SerializeObject(item.SqlList),
                BIMainTableId = mainTableId,
                ContainerId = containerId,
                Sort = sort
            });
        }

        /// <summary>
        /// 保存表格子项
        /// </summary>
        public async Task SaveTableAsync(
            DashboardItemDto item,
            int containerId,
            int mainTableId,
            int sort)
        {
            const string sql = @"
INSERT INTO SEBI_TableConfig (
    cId, Type, Span, Height, TitleName, TitleColor, TitleSize,
    TableHeight, ScrollSpeed, UpdateKey, Header, Data, [Index],
    ColumnWidth, Align, HeaderBgColor, RowBgColors, TextStyle,
    Decoration, BackgroundColor, BackgroundStyle, SqlList,
    BIMainTableId, ContainerId, Sort,prop,oddRowBGC,evenRowBGC,visibleRows,indexColumnWidth
) VALUES (
    @cId, @Type, @Span, @Height, @TitleName, @TitleColor, @TitleSize,
    @TableHeight, @ScrollSpeed, @UpdateKey, @Header, @Data, @Index,
    @ColumnWidth, @Align, @HeaderBgColor, @RowBgColors, @TextStyle,
    @Decoration, @BackgroundColor, @BackgroundStyle, @SqlList,
    @BIMainTableId, @ContainerId, @Sort,@prop,@oddRowBGC,@evenRowBGC,@visibleRows,@indexColumnWidth
)";

            using var connection = new SqlConnection(_connectionString);
            await connection.ExecuteAsync(sql, new
            {
                cId = item.Id,
                item.Type,
                item.Span,
                item.Height,
                TitleName = item.Title,
                item.TitleColor,
                item.TitleSize,
                item.TableHeight,
                item.ScrollSpeed,
                item.UpdateKey,
                Header = JsonConvert.SerializeObject(item.Header),
                Data = JsonConvert.SerializeObject(item.TableData),
                item.Index,
                ColumnWidth = JsonConvert.SerializeObject(item.ColumnWidth),
                Align = JsonConvert.SerializeObject(item.Align),
                item.HeaderBgColor,
                item.oddRowBGC,
                item.evenRowBGC,
                item.visibleRows,
                item.indexColumnWidth,
                RowBgColors = JsonConvert.SerializeObject(item.RowBgColors),
                TextStyle = JsonConvert.SerializeObject(item.TextStyle),
                Decoration = JsonConvert.SerializeObject(item.Decoration),
                item.BackgroundColor,
                item.BackgroundStyle,
                SqlList = JsonConvert.SerializeObject(item.SqlList),
                prop = JsonConvert.SerializeObject(item.prop),
                BIMainTableId = mainTableId,
                ContainerId = containerId,
                Sort = sort
            });
        }

        public async Task SavePieChartAsync(
    DashboardItemDto item,
    int containerId,
    int mainTableId,
    int sort)
        {
            const string sql = @"
INSERT INTO SEBI_PieConfig (
    cId, Type, Span, Height, TitleName, TitleColor, TitleSize,
    BackgroundColor, BackgroundStyle, SqlList, Data, Radius, LabelShow,
    BIMainTableId, ContainerId, Sort
) VALUES (
    @cId, @Type, @Span, @Height, @TitleName, @TitleColor, @TitleSize,
    @BackgroundColor, @BackgroundStyle, @SqlList, @Data, @Radius, @LabelShow,
    @BIMainTableId, @ContainerId, @Sort
)";

            using var connection = new SqlConnection(_connectionString);
            await connection.ExecuteAsync(sql, new
            {
                cId = item.Id,
                item.Type,
                item.Span,
                item.Height,
                TitleName = item.Title,
                item.TitleColor,
                item.TitleSize,
                item.BackgroundColor,
                item.BackgroundStyle,
                SqlList = JsonConvert.SerializeObject(item.SqlList),
                Data = JsonConvert.SerializeObject(item.PieRingData), // 序列化饼图数据
                Radius = JsonConvert.SerializeObject(item.Radius), // 序列化半径配置
                item.LabelShow,
                BIMainTableId = mainTableId,
                ContainerId = containerId,
                Sort = sort
            });
        }

        /// <summary>
        /// 保存环形图子项
        /// </summary>
        public async Task SaveRingChartAsync(
            DashboardItemDto item,
            int containerId,
            int mainTableId,
            int sort)
        {
            const string sql = @"
INSERT INTO SEBI_RingConfig (
    cId, Type, Span, Height, TitleName, TitleColor, TitleSize,
    BackgroundColor, BackgroundStyle, SqlList, Data, Radius, LabelShow,
    BIMainTableId, ContainerId, Sort
) VALUES (
    @cId, @Type, @Span, @Height, @TitleName, @TitleColor, @TitleSize,
    @BackgroundColor, @BackgroundStyle, @SqlList, @Data, @Radius, @LabelShow,
    @BIMainTableId, @ContainerId, @Sort
)";

            using var connection = new SqlConnection(_connectionString);
            await connection.ExecuteAsync(sql, new
            {
                cId = item.Id,
                item.Type,
                item.Span,
                item.Height,
                TitleName = item.Title,
                item.TitleColor,
                item.TitleSize,
                item.BackgroundColor,
                item.BackgroundStyle,
                SqlList = JsonConvert.SerializeObject(item.SqlList),
                Data = JsonConvert.SerializeObject(item.PieRingData), // 序列化环形图数据
                Radius = JsonConvert.SerializeObject(item.Radius), // 序列化内外半径配置
                item.LabelShow,
                BIMainTableId = mainTableId,
                ContainerId = containerId,
                Sort = sort
            });
        }

        /// <summary>
        /// 保存文本组件
        /// </summary>
        public async Task SaveTextAsync(
            DashboardItemDto item,
            int containerId,
            int mainTableId,
            int sort)
        {
            const string sql = @"
INSERT INTO SEBI_TextConfig (
    cId, Type, Span, Height, TitleName, TitleColor, TitleSize,
    BackgroundColor, BackgroundStyle, SqlList, Content, TextAlign,
    FontSize, FontWeight, FontColor, LineHeight,
    BIMainTableId, ContainerId, Sort
) VALUES (
    @cId, @Type, @Span, @Height, @TitleName, @TitleColor, @TitleSize,
    @BackgroundColor, @BackgroundStyle, @SqlList, @Content, @TextAlign,
    @FontSize, @FontWeight, @FontColor, @LineHeight,
    @BIMainTableId, @ContainerId, @Sort
)";

            using var connection = new SqlConnection(_connectionString);
            await connection.ExecuteAsync(sql, new
            {
                cId = item.Id,
                item.Type,
                item.Span,
                item.Height,
                TitleName = item.Title,
                item.TitleColor,
                item.TitleSize,
                item.BackgroundColor,
                item.BackgroundStyle,
                SqlList = JsonConvert.SerializeObject(item.SqlList), // 序列化SQL列表
                item.Content,
                item.TextAlign,
                item.FontSize,
                item.FontWeight,
                item.FontColor,
                item.LineHeight,
                BIMainTableId = mainTableId,
                ContainerId = containerId,
                Sort = sort
            });
        }

        public async Task<int> SaveBeforeSelectByName(string name)
        {
            // 检查输入参数是否为空
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("名称不能为空", nameof(name));
            }

            using var connection = new SqlConnection(_connectionString);
            try
            {
                // 打开数据库连接
                await connection.OpenAsync();

                // 执行查询，检查同名记录数量
                int count = await connection.QueryFirstOrDefaultAsync<int>(
                    "select count(*) from SEBI_BIMainTable where Name = @name",
                    new { name } // 参数化查询，防止SQL注入
                );

                // 返回查询到的记录数量
                return count;
            }
            catch (SqlException ex)
            {
                // 处理数据库异常
                throw new Exception("查询数据库时发生错误", ex);
            }
        }

        /// <summary>
        /// 获取配置（简化实现）
        /// </summary>
        public async Task<DashboardConfigDto> GetConfigAsync(int mainTableId)
        {
            // 实际项目中需要从数据库查询并组装完整配置
            using var connection = new SqlConnection(_connectionString);
            var mainConfig = await connection.QueryFirstOrDefaultAsync<DashboardConfigDto>(
                "SELECT * FROM SEBI_BIMainTable WHERE Id = @Id",
                new { Id = mainTableId });

            if (mainConfig == null) return null;

            // 查询容器列表
            var containers = await connection.QueryAsync<DashboardContainerDto>(
                "SELECT * FROM SEBI_Container WHERE BIMainTableId = @MainId",
                new { MainId = mainTableId });

            mainConfig.Items = containers.ToList();
            return mainConfig;
        }
    }
}
